import time

from appium import webdriver
import os
import subprocess
import yaml
from config.GlobalVar import G
from handler.LoggerHandler import logger


# 公共的BaseDriver类
# serverPort：appium服务占用端口号
# deviceName：设备的udid
class BaseDriver:
    def __init__(self, device_info):
        self.log = logger()
        self.device_info = device_info

    def get_base_driver(self):
        # 配置yaml文件路径
        DESIRED_CAPS_PATH = os.path.join(G.BASE_PATH, "yaml", "desired_caps.yaml")

        with open(DESIRED_CAPS_PATH, encoding='utf-8') as file:
            data = yaml.load(file, Loader=yaml.FullLoader)

        self.log.info("读取配置文件成功！")

        desired_capabilities = {
            'platformName': data['platformName'],
            'platformVersion': self.device_info["platformVersion"],
            'deviceName': self.device_info["deviceName"],
            'appPackage': data['appPackage'],
            'appActivity': data['appActivity'],
            'automationName': data['automationName'],
            'autoGrantPermissions': data['autoGrantPermissions'],  # 自动授权app权限
            'unicodeKeyboard': data['unicodeKeyboard'],
            'resetKeyboard': data['resetKeyboard']
        }
        print(desired_capabilities)
        driver = webdriver.Remote('http://127.0.0.1:{0}'.format(str(self.device_info["serverPort"])), desired_capabilities)
        driver.implicitly_wait(G.IMPLICITLY_WAIT_TIME)  # 隐式等待时间
        self.log.info("打开APP成功！")
        return driver